//
//  申请退货Ctr-ext.swift
//  smosky
//
//  Created by zhuxietong on 2018/8/6.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import soapp
import Eelay
import MBProgressHUD

extension AfterApplyStep2{
    @objc func beginSubmit() {
        
        
        let ids = selectedGoodsIDs
        if ids.count < 1 {
            "请选择商品".loc.alert()
            return
        }
        //        let ctr = SaleAfterDetailCtr()
        //        ctr.mo.model = mo.model
        //        ctr.afterType = serverType
        //        navigationController?.pushViewController(ctr, animated: true)
        //        return
        let info = JoPaw.paw(tableView: tableView)
        if info.validate{
            var values = info.values
            let price = info.values.mutable_dictionary[float:"price",0]
            //            print("========|\(price)=======|\(maxReturnPrice)")
            let str = "最多可退款[XX]¥,请修改退款金额".replaceVars(values: price.price_display)
            if price > maxReturnPrice{
                JoAlertView(info: "提示".loc,str).append(title: "确定".loc, style: .destructive) {
                    
                    }.show(at: self)
                return
            }
            values["orderid"] = self.orderID
            values["goodsids"] = ids.joined(separator: ",")
            values["rtype"] = self.serverType.rawValue
            
            //            print("======iiiiisiis|\(info.values)")
            
            var files = [[String:Any]]()
            if let imgs = values["images"] as? String
            {
                
                (imgs.JsonArray ?? NSMutableArray()).list({ (one:NSMutableDictionary, i) in
                    if one["path",""].len > 2
                    {
                        files.append(
                            [
                                "path":one["path",""],
                                ]
                        )
                    }
                    if one["__url",""].len > 2//已经上传过有url路径
                    {
                        files.append(
                            [
                                "__url":one["__url",""],
                                ]
                        )
                    }
                })
                values.removeValue(forKey: "images")
            }
            let ps = values
            uploadFiles(values: ps, files: files)
        }
    }
    
    
    func uploadFiles(values:[String:Any],files:[[String:Any]]) {
        if files.count < 1
        {
            var vs = values
            vs["imgs"] = "[]"
            commitAction(params: vs)
            return
        }
        
        let ls = files.mutable_array
        
        let tasks = ls.map { (one) -> UploadImageTask in
            let task = UploadImageTask()
            task.url = _SURL.uploadImage.url
            task.model = one as! NSMutableDictionary
            return task
        }
        
        weak var wself = self
        
        
        var hud:MBProgressHUD? = MBProgressHUD.init(view:wself!.navigationController!.view.window!)
        if hud == nil{
            hud = MBProgressHUD.showAdded(to: wself!.navigationController!.view.window!, animated: true)
        }
        
        //        navigationController?.view.isUserInteractionEnabled = false
        
        hud?.minSize = [150,100]
        hud?.label.text = "正在上传图片".loc
        hud?.mode = .indeterminate
        
        AsyncQue.default.start(tasks: tasks) { (progress) in
            switch progress  {
            case .failed(count: _, task: _):
                hud?.hide(animated: true)
                "文件上传失败,请重试".loc.alert()
            case .success:
                var img_urls = [String]()
                for one in tasks{
                    img_urls.append(one.model["__url",""])
                }
                var vs = values
                vs["imgs"] = img_urls.rawJson ?? "[]"
                //                vs["thumbs"] = img_urls.joined(separator: "|")
                wself?.commitAction(params: vs)
            case .continue(count: let i, task:_):
                hud?.label.text = "\("正在上传图片".loc)(\(i)/\(tasks.count))"
                break
            }
        }
    }
    
    func commitAction(params:[String:Any]) {
        
        //        print("-ss----|\(params)")
        weak var wself = self
        var hud:MBProgressHUD? = MBProgressHUD.init(view: wself!.navigationController!.view.window!)
        if hud == nil{
            hud = MBProgressHUD.showAdded(to: wself!.navigationController!.view.window!, animated: true)
        }
        
        hud?.label.text = "正在提交信息".loc
        JoTask().post.log._surl(.提交售后申请).params(params).json_handle { (status, msg, obj, resp) in
            if status.isSuccess{
                if let ID = DataNode<String>.path(node: "refundid", obj){
                    hud?.hide(animated: true)
                    __post(notify: Goods.Notice.goodsOrderChange)
                    wself?.success(id: ID)
                    return
                }
            }
            hud?.__show(msg, image: nil, minSize: nil)
            }.run()
    }
    
    func success(id:String) {
        "提交成功请等待商家的受理反馈！".loc.alert()
        let ctr = SaleAfterDetailCtr()
        ctr.mo.model = ["id":id].mutable_dictionary
        ctr.presentType = .navRootPresent
        let nav = RootNavigationController(rootViewController: ctr)
        weak var wself = self
        self.navigationController?.present(nav, animated: true, completion: {
            wself?.popController(1)
        })
        
    }
    
}

